package homegroup.inc.dao;

import homegroup.inc.dto.Book;

import javax.ejb.Stateless;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Stateless
public class BookDAO extends BaseDAO {
    private Book book = null;

    public void create(Book aBook) {
        entityManager.persist(aBook);
    }

    public Book findById(int key) {
        book = entityManager.find(Book.class, key);
        return book;
    }

//    public List<Book> findByISBN(String isbn) {
//        String q = "select b from Book b  where b.ISBN like '%" + isbn + "%'";
//        Query query = entityManager.createQuery(q);
//        List<Book> books = query.getResultList();
//        return books;
//    }

    public Book findByISBN(String isbn) {
        String q = "select b from Book b  where b.ISBN like '%" + isbn + "%'";
        TypedQuery<Book> query = entityManager.createQuery(q, Book.class);
        Book book = query.getSingleResult();
        return book;
    }

    public void update(Book aBook) {
        entityManager.merge(aBook);
    }

    public void delete(Book aBook) {
        Book  book = entityManager.merge(aBook);
    }

    /**
     * Returns retrieved objects
     * @param portionSize amount of a quested objects that could be retrieved by one
     * @param offset offset for whole ResultSet, using offset we can navigate through needed data
     * @return quested objects
     */
    public List<Book> getAllByPortion(int  portionSize, int offset) {
        String q = "select b from Book b";
        Query query = entityManager.createQuery(q);
        query.setMaxResults(portionSize);
        query.setFirstResult(offset);
        List<Book> books = query.getResultList();
        return books;
    }

    public List<Book> getPortionOfBooks(int  portionSize, int offset) {
        String q = "select b from Book b";
        Query query = entityManager.createQuery(q);
        query.setMaxResults(portionSize);
        query.setFirstResult(offset);
        List<Book> books = query.getResultList();
        return books;
    }

    public List<Book> getAll() {
        String q = "select b from Book b";
        Query query = entityManager.createQuery(q);
        List<Book> books = query.getResultList();
        return books;
    }

    public long recordsCounter() {
        String q = "select count(b) from Book b";
        Query query = entityManager.createQuery(q);
//        TypedQuery<Integer> query = entityManager.createQuery(q, Integer.class);
        long recordsAmount = (long)query.getSingleResult();
        return recordsAmount;
    }
}